package com.uh.microservice.core.service;


import com.uh.microservice.core.CONSTANTS;
import com.uh.microservice.core.dao.JdbcDao;
import com.uh.microservice.core.enums.DeletedEnum;
import com.uh.microservice.core.exception.BusinessException;
import com.uh.microservice.core.util.BeanUtil;
import com.uh.microservice.core.util.CacheUtil;
import com.uh.microservice.core.util.ValidatePrm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公用Service
 * Created by fll on 2017/10/17.
 */
@Service
public class PublicService {

    @Autowired
    private JdbcDao jdbcDao;
    @Autowired
    private ScriptComponent scriptCmp;

    /**
     * 根据条件查询结果（不分页）
     *
     * @param inputParam CODE ->sqlName DATA ->查询参数
     * @param user       当前的登录用户
     * @return
     */
    public List queryList(Map inputParam) {
        String sqlName = (String) inputParam.get("CODE");
        Map dataParam = (Map) inputParam.get("DATA");
        if (dataParam == null) {
            dataParam = new HashMap();
        }
        dataParam.put("DELETED", DeletedEnum.NO.key);
        return jdbcDao.loadListByCode(sqlName, dataParam);

    }

    /**
     * 根据条件查询结果（分页）
     *
     * @param inputParam 不为空
     * @return
     */
    public Map queryPage(String sqlName, Map inputParam) {
        Map inputData = new HashMap();
        if (inputParam.get("DATA") != null) {
            inputData = (Map) inputParam.get("DATA");
        }
        inputData.put("DELETED", DeletedEnum.NO.key);
        return jdbcDao.loadPage(sqlName, inputData, inputParam);
    }


    /**
     * 基础操作（增删改）
     *
     * @param inputParam
     * @return
     */
    @Transactional
    public Map execute(Map inputParam) {
        //表名字
        String tableName = (String) inputParam.get("CLZ");

        //操作类型
        String operate = (String) inputParam.get("CODE");
        operate = StringUtils.isEmpty(operate) ? CONSTANTS.NULL : operate;
        //js操作
        String script = (String) inputParam.get("SCRIPT");
        //参数
        Map dataParam = (Map) inputParam.get("DATA");
        //返回值
        Map returnMap = new HashMap();

        if (!CONSTANTS.RULE.equals(operate)) {
            Object checkResult = operateCheck(script, dataParam);
            if (CONSTANTS.NULL.equals(operate) && checkResult != null) {
                //接受js返回值
                returnMap.putAll((Map) checkResult);
            }

        }
        switch (operate) {
            case CONSTANTS.ADD:
                vertifyField(tableName, dataParam);
                returnMap = jdbcDao.add(tableName, dataParam);
                break;
            case CONSTANTS.UPDATE:
                vertifyField(tableName, dataParam);
                returnMap = jdbcDao.update(tableName, dataParam);
                break;
            case CONSTANTS.DEL: //假删
                jdbcDao.del(tableName, dataParam);
                returnMap.putAll(dataParam);
                break;
            case CONSTANTS.REMOVE: //真删
                jdbcDao.remove(tableName, dataParam);
                returnMap.putAll(dataParam);
                break;
            case CONSTANTS.RULE:
                Map params = new HashMap();
                params.put("db", jdbcDao);
                params.put("prm", dataParam);
                returnMap.put("RULE", scriptCmp.excute(script, params));
                break;
            default:
                break;

        }

        // 操作表为字典表时，清除支付类型缓存
        if ("SYS_DICTIONARY".equals(tableName)) {
            CacheUtil.instance().removeKey(CacheUtil.CACHE_NAME_SPACE_PAY_TYPE);
        }

        return returnMap;
    }


    public void vertifyField(String tableName, Map dataParam) {
        //针对 CODE NAME 进行判断
        Map<String, String> fields = ValidatePrm.getInstance().getAdminVerifyParam(tableName);
        fields.forEach((key, value) -> {
            {
                if (dataParam.containsKey(key)) {
                    Map result = jdbcDao.loadRowByField(tableName, key, dataParam.get(key));
                    if (result != null && !result.get(CONSTANTS.C_PK).equals(dataParam.get(CONSTANTS.C_PK))) {
                        throw new BusinessException(value + "已存在");
                    }
                }

            }
        });
    }


    /**
     * 操作前检查
     *
     * @param script
     * @param dataParam
     */
    private Object operateCheck(String script, Map dataParam) {
        if (script == null || script == "") {
            return null;
        }
        Map params = new HashMap();
        params.put("db", jdbcDao);
        params.put("prm", dataParam);
        return scriptCmp.excute(script, params);

    }


    /**
     * 根据ID获取记录
     *
     * @param InputParam clz、id
     * @return
     */
    public Map getById(Map InputParam) {
        String tableName = (String) InputParam.get("CLZ");
        String code = (String) InputParam.get("CODE");
        String id = (String) ((Map<String, Object>) InputParam.get("DATA")).get("ID");
        if (StringUtils.isNotEmpty(tableName)) {
            Assert.notNull(id, "id must not null");
            return jdbcDao.loadRT(tableName, id);
        } else {
            return jdbcDao.loadRowByCode(code, (Map) InputParam.get("DATA"));
        }
    }

    public List queryTree(Map inputParam) {
        List list = this.queryList(inputParam);
        return BeanUtil.list2Tree(list);
    }

    /**
     * 根据字典类别获取字典信息
     *
     * @param typeValue
     * @return
     */
    public List<Map> queryDictList(String typeValue) {
        List<Map> dicts = jdbcDao.loadListByCode("query_dictionary_type_list", new HashMap() {{
            put("TYPE_VALUE", typeValue);

        }});

        return dicts;
    }
}
